"""
问答相关接口
"""
import json
from fastapi import APIRouter, HTTPException
from fastapi.responses import StreamingResponse
from app.models.request import QueryRequest
from app.services.retrieval import create_retrieval_service
from app.services.chat import chat_service

router = APIRouter()


@router.post("/query")
async def query_with_stream(request: QueryRequest):
    """
    提交问题，获取基于知识库的答案（流式响应）
    
    - **question**: 用户问题
    
    返回 Server-Sent Events 流式响应：
    - event: content - AI 生成的答案片段
    - event: metadata - 检索上下文和相似度信息
    - event: done - 响应结束标识
    """
    try:
        # 创建检索服务
        retrieval_service = create_retrieval_service()
        
        # 检索相关文本块
        texts, scores, documents = retrieval_service.retrieve(request.question)
        
        if not texts:
            raise HTTPException(status_code=404, detail="知识库为空，请先上传文本文件")
        
        # 构建上下文
        context = "\n".join(texts)
        
        async def event_generator():
            """生成 SSE 事件流"""
            # 首先流式发送答案内容
            for content_chunk in chat_service.generate_answer_stream(request.question, context):
                # 发送 content 事件
                yield f"event: content\ndata: {json.dumps({'content': content_chunk}, ensure_ascii=False)}\n\n"
            
            # 答案发送完成后，发送元数据
            metadata = {
                "context": [
                    {
                        "text": text,
                        "similarity": score,
                        "document": doc
                    }
                    for text, score, doc in zip(texts, scores, documents)
                ],
                "similarity_scores": scores
            }
            yield f"event: metadata\ndata: {json.dumps(metadata, ensure_ascii=False)}\n\n"
            
            # 最后发送完成事件
            yield f"event: done\ndata: {json.dumps({'status': 'completed'}, ensure_ascii=False)}\n\n"
        
        return StreamingResponse(
            event_generator(),
            media_type="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "X-Accel-Buffering": "no"  # 禁用 Nginx 缓冲
            }
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"查询时发生错误: {str(e)}")

